package com.sx.service.user;

import com.sx.basic.exception.BasicException;
import com.sx.basic.service.BasicService;
import com.sx.basic.service.impl.BasicServiceImpl;
import com.sx.dao.user.RelationRepository;
import com.sx.entity.user.RelationEntity;
import com.sx.utils.TaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author AdinZ
 * @date 2020/11/18 14:25
 */
@Service
public class RelationService extends BasicServiceImpl<RelationRepository, RelationEntity,Long>
        implements BasicService<RelationEntity,Long>,IRelationService {

    /**
     * 查找用户的邀请人 第一次邀请人
     *
     * @param uid 用户id
     * @return
     */
    @Override
    public Long findInvite(long uid) {
        return this.findInvite(uid, 0);
    }

    /**
     * 查找我的邀请人
     *
     * @param uid   我的id
     * @param level 层级
     * @return 邀请人, 正常情况下,相同层级,只会有一个人, 出现2个以上,选择第一个
     */
    @Override
    public Long findInvite(long uid, int level) {
        Object inviteObj = this.redisService.get(RelationEntity.KEY, uid + "_" + level);
        Long invite;
        if (inviteObj == null) {
            List<RelationEntity> list = this.repository.findInvite(uid, level);
            if (list == null || list.size() == 0) return null;
            invite = list.get(0).getInviteUid();
            this.redisService.set(RelationEntity.KEY, uid + "_" + level, invite+"");
        }else {
            invite=Long.parseLong(inviteObj.toString());
        }
        return invite;
    }

    /**
     * 注册关系用户表
     * @param inviteUid 邀请用户id
     * @param uid       注册用户id
     * @param length    关系链长度
     */
    @Override @Transactional
    public void registered(long inviteUid, long uid,int length) {
        List<RelationEntity> list = new ArrayList<>();
        //推荐人列表, 如果有重复说明有死循环
        Set<Long> set = new HashSet<>();
        int index = 0;
        Long invite = inviteUid;
        while (invite != null) {
            if(index>length)break;
            list.add(new RelationEntity(invite, uid, index));
            if (set.contains(invite)) throw new BasicException("邀请码关系链有错误");
            set.add(invite);
            index++;
            invite = this.findInvite(invite);

        }
        this.save(list);
    }



}
